package de.grosjohann.android.feuerwehr.fms;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

public class FMSWsClient {

  public static final String MEDIA_TYPE = "application/json";

  private final HttpClient hc;
  private final String uri;

  FMSWsClient(String newUri, int connectionTimeout, int socketTimeout) throws ClientProtocolException, IOException {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    hc = new DefaultHttpClient(httpParameters);
    uri = newUri;
  }

  String get() throws ClientProtocolException, IOException, HttpException {
    HttpGet httpGet = new HttpGet(uri);
    httpGet.setHeader("Accept", FMSWsClient.MEDIA_TYPE);
    HttpResponse resp = hc.execute(httpGet);

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      return EntityUtils.toString(resp.getEntity());
    }

    throw new HttpException(httpGet.getURI().toString() + " " + resp.getStatusLine().getReasonPhrase() + " ("
        + resp.getStatusLine().getStatusCode() + ")");
  }

  String post(String authorization, String status) throws ClientProtocolException, IOException, HttpException {
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setHeader("Accept", FMSWsClient.MEDIA_TYPE);
    httpPost.setHeader("Authorization", authorization);

    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new BasicNameValuePair("status", status));
    httpPost.setEntity(new UrlEncodedFormEntity(postParams));

    HttpResponse resp = hc.execute(httpPost);

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      return EntityUtils.toString(resp.getEntity());
    }

    throw new HttpException(resp.getStatusLine().getStatusCode() + "");
  }

}
